import React, { useEffect, useState } from 'react';
import { Menu } from 'antd';
import {
  HomeOutlined,
  ProjectOutlined,
  AppstoreOutlined,
  UserOutlined,
  TeamOutlined,
} from '@ant-design/icons';
import { connect } from 'dva';
import Icon from './icon';
import './index.less';

const SidBar = ({ dispatch, list = [], active }) => {
  const { SubMenu } = Menu;
  const [mode] = React.useState('inline');
  const [theme] = React.useState('light');
  const [privilegeList, setList] = useState([]);
  const defaultOpenKeys = location.hash.slice(2).split('/');
  useEffect(() => {
    const privilegeList = sessionStorage.getItem('privilegeList') || '[]';
    setList(JSON.parse(privilegeList));
  }, []);
  function handleClick(e) {
    console.log('click', e);
    dispatch({
      type: '$router/forward',
      payload: {
        url: e.keyPath.reverse().join('/'),
      },
    });
  }
  const selectedKeys = active ? active.split('/') : defaultOpenKeys[1];
  //首页特殊处理
  const homePrivite = [
    'see_analysis_chart',
    'see_pending',
    'see_notice',
    'see_law',
    'see_table',
  ].some(child => privilegeList.some(item => item.code == child));
  // homePrivite &&
  privilegeList.push({ code: 'home' });
  return (
    <div className="sidbar">
      <Menu
        onClick={handleClick}
        style={{ width: 180 }}
        mode={mode}
        theme={theme}
        defaultOpenKeys={defaultOpenKeys}
        selectedKeys={selectedKeys}
      >
        {list
          .filter(
            menu =>
              (menu.role == 'home' && homePrivite) ||
              (menu.children &&
                menu.children.some(child =>
                  privilegeList.some(item => item.code == child.role),
                )),
          )
          .map((menu, index) => {
            return menu.children ? (
              <SubMenu
                icon={
                  <Icon
                    menu={menu}
                    selectedKeys={
                      active ? active.split('/')[0] : defaultOpenKeys[0]
                    }
                  />
                }
                title={menu.name}
                key={menu.key}
              >
                {menu.children &&
                  menu.children.map(child => {
                    const authed = privilegeList.some(
                      item => item.code == child.role,
                    );
                    return authed ? (
                      <Menu.Item key={child.key}>{child.name}</Menu.Item>
                    ) : null;
                  })}
              </SubMenu>
            ) : (
              <Menu.Item
                title={menu.name}
                icon={<HomeOutlined />}
                key={menu.key}
              >
                {menu.name}
              </Menu.Item>
            );
          })}
      </Menu>
    </div>
  );
};
export default connect(state => state['$router'])(SidBar);
